package com.liu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.liu.common.R;
import com.liu.entity.User;
import com.liu.service.UserService;
import com.liu.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
     private RedisTemplate<String, Object> redisTemplate;

    /**
     * 发送短信验证码
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        //获取手机号
        String phone = user.getPhone();

        if (StringUtils.isNotEmpty(phone)) {

            //生成随机的6位验证码
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            log.info("生成的验证码为：" + code);

            //调用阿里云提供的短信服务API完成发送短信
            //SMSUtils.sendMessage("瑞吉外卖","",phone,code);

            //需要将生成的验证码保存到Session
            //session.setAttribute(phone, code);

            //将生成的验证码存入Redis中，并设置有效期为5分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

            return R.success("短信发送成功");

        }

        return R.error("短信发送失败");

    }


    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        //获取手机号
        String phone = (String) map.get("phone");

        //获取验证码
        String code = (String) map.get("code");

        //获取保存在session中的验证码
        //String codeInSession = (String) session.getAttribute(phone);

        //从Redis中获取验证码
        Object codeInSession = redisTemplate.opsForValue().get(phone);

        //验证码校验
        if (codeInSession != null && codeInSession.equals(code)) {
            //如果登录成功，从数据库查询用户信息

            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getPhone, phone);

            //判断是否是新用户第一次登录，如果是则自动注册
            User user = userService.getOne(lambdaQueryWrapper);
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //将用户信息保存到session中
            session.setAttribute("user", user.getId());

            //删除Redis中的验证码
            redisTemplate.delete(phone);

            return R.success(user);
        }
        return R.error("验证码错误,登录失败");

    }

    @PostMapping("/loginout")
    public R<String> logout(HttpSession session) {
        //清除session中的用户信息
        session.removeAttribute("user");
        return R.success("退出成功");
    }


}
